package com.infodeli.user.login.service.impl;

import com.infodeli.common.exception.ExceptionEnum;
import com.infodeli.common.exception.LoginException;
import com.infodeli.common.exception.ServiceException;
import com.infodeli.common.utils.ComTool;
import com.infodeli.common.utils.ServiceExceptionUtils;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infodeli.common.utils.PageUtils;
import com.infodeli.common.utils.Query;

import com.infodeli.user.login.dao.UserDao;
import com.infodeli.user.login.entity.UserEntity;
import com.infodeli.user.login.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    public UserEntity doLogin(UserEntity user){
        // 基本的非空判断
        if(user.getStuid() == null || user.getStuid().trim().length() == 0){
            throw getLoginException(ExceptionEnum.USERNAME_EMPTY);
        }else if(user.getStuid().trim().length() <9 || user.getStuid().trim().length() > 10) {
            throw getLoginException(ExceptionEnum.USERNAME_ERROR);
        }else if(user.getPassword() == null || user.getPassword().trim().length() == 0){
            throw getLoginException(ExceptionEnum.PASSWORD_EMPTY);
        }else if(user.getPassword().trim().length() < 6){
            throw getLoginException(ExceptionEnum.PASSWORD_MIN_SIX);
        }
        // 执行查询
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("stuid", user.getStuid());
        UserEntity one = this.getOne(wrapper);
        // 进一步判断
        if(one == null){
            // 不存在
            throw getLoginException(ExceptionEnum.USER_NOT_EXIST);
        }else if(!one.getPassword().equals(ComTool.getMd5Str(user.getPassword()))){
            // 密码错误
            throw getLoginException(ExceptionEnum.PASSWORD_ERROR);
        }else if(one.getUserStatus() == 0 && one.getFreeTime().compareTo(ComTool.getDateStr()) > 0){
            // 账号封禁
            throw getLoginException(ExceptionEnum.USER_BAN, one.getFreeTime());
        }
        return one;
    }

    // 用于生成 jwt 的 payload
    @Override
    public Map<String, String> getUserMap(UserEntity user) {
        Map<String, String> userMap = new HashMap<>();
        userMap.put("uid", user.getUid().toString());
        userMap.put("stuid", user.getStuid());
        userMap.put("nickName", user.getNickName());
        return userMap;
    }

    @Override
    public void register(UserEntity user) {
        UserEntity one = this.getOne(new QueryWrapper<UserEntity>().eq("stuid", user.getStuid()));
        if(one != null){
            throw getLoginException(ExceptionEnum.USER_EXIST);
        }
        initUser(user);
        this.save(user);
    }

    @Override // 认证身份（通过密码）
    public void authPassword(UserEntity user) {
        UserEntity byId = this.getById(user.getUid());
        if(byId == null){
            throw ServiceExceptionUtils.getServiceException(ExceptionEnum.LOCAL_AUTH_NOT_EXIST);
        }else if(!byId.getPassword().equals(user.getPassword()) ){
            throw ServiceExceptionUtils.getServiceException(ExceptionEnum.LOCAL_AUTH_PASSWORD_ERROR);
        }
    }

    public void initUser(UserEntity user){
        user.setPassword(ComTool.getMd5Str(user.getPassword()));
        user.setUserStatus(1);
        user.setPortrait("");
        user.setRegisterTime(ComTool.getDateStr());
        user.setFreeTime("");
    }

    public LoginException getLoginException(ExceptionEnum eEnum){
        return new LoginException(eEnum.getCode(), eEnum.getMsg());
    }
    public LoginException getLoginException(ExceptionEnum eEnum, String msg){
        return new LoginException(eEnum.getCode(), eEnum.getMsg()+"="+msg);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String useUid = (String) params.get("useUid");
        if(Integer.parseInt(useUid) == 1){
            wrapper.eq("uid", key);
        }else{
            if(key != null && !"".equals(key)){
                wrapper.eq("stuid", key).or().like("nick_name", key);
            }
        }

        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

}